import {systemNo} from '../config/defaultSettings'
import moment from 'moment'
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

function isNullObj(obj) {
  if (obj == null || obj == "" || obj.length == 0) {
    return true;
  } else {
    return false;
  }
}
/**
 * 表单验证
 * @param {*} formObj 
 */
function formVerify(formObj){
  //这里进行验证
  let flag = true
  formObj.setData({errorMessage:""});
  if(!isNullObj(formObj.data.field["rules"])){
    let rules = formObj.data.field["rules"];
    let len = rules.length;
    for(let i=0;i<len;i++){
      if(rules[i]["required"]){
        //如果是必填
        if(isNullObj(formObj.data.formData[formObj.data.field['field']+formObj.data.betweenSign])){
          formObj.setData({errorMessage:rules[i]["message"]});
          flag = false
          break;
        }
      }
      if(rules[i]["regExp"]){
        //配置的正则表达式，注意特殊字符 特别是\ 记得用\\代替
        //自定义验证
        let regex = new RegExp(rules[i]["regExp"])
        // console.log(regex)
        if(!regex.test(formObj.data.formData[formObj.data.field['field']+formObj.data.betweenSign])){
          formObj.setData({errorMessage:rules[i]["message"]});
          flag = false
          break;
        }
      }
    }
  }

  return flag
}
function request(paramObj){
  //访问地址不能为空
  if(isNullObj(paramObj) || isNullObj(paramObj["url"])){
    wx.showToast({
      title: '访问地址为空',
      mask:true,
      icon:'error',
    });
    return false
  }
  let method_ = "post"
  let token_ = wx.getStorageSync("Access-Token") ? wx.getStorageSync("Access-Token")  : ''
  let systemNo_ = paramObj["systemNo"] ? paramObj["systemNo"] : systemNo
  let data_ = paramObj["data"] || {}
  if(!isNullObj(paramObj["method"])){
    method_ = paramObj["method"]
  }
  return new Promise((resolve,reject)=>{
    wx.request({
      url: paramObj["url"],
      method:method_,
      data:data_,
      header: {
        'Content-Type': 'application/json; charset=UTF-8', // 默认值
        "Access-Token": token_,
        "systemNo": systemNo_
      },
      success:(res)=>{
        resolve(res.data)
      },
      fail: ()=>{
        wx.showToast({
          title: '请求错误',
          icon:'none'
        })
        reject('请求错误')
      }

    })
  })
}

function date2String(d,mode){
  if(d){
     if(mode=='date'){
      return moment(d).locale('zh-cn').format('YYYY-MM-DD')
     }else if(mode=='year-month'){
      return moment(d).locale('zh-cn').format('YYYY-MM')
     }else if(mode=="datetime"){
      return moment(d).locale('zh-cn').format('YYYY-MM-DD HH:mm:ss')
     }else if(mode=="time"){
      return d
     }
  }else{
    return null
  }
}
function string2Date(s,mode){
  if(s){
    if(mode=='date'){
      return moment(s,'YYYY-MM-DD').locale('zh-cn').toDate().valueOf()
    }else if(mode=='year-month'){
      return moment(s,'YYYY-MM').locale('zh-cn').toDate().valueOf()
    }else if(mode=='datetime'){
      return moment(s,'YYYY-MM-DD HH:mm:ss').locale('zh-cn').toDate().valueOf()
    }else if(mode=='time'){
      return s
    }
  }else{
    return null
  }
}

/**
 * 一次传入多个字典编码,将编码对应的显示值给生成并存起来
 * @param {*} dictCodes
 */
function setDictTextInfo(dictCodes){
  if(!dictCodes){
    return
  }
  let dictTextInfo = getApp().globalData.dictTextInfo
  let dictInfo = getApp().globalData.dictInfo
  let dictCodeArr = dictCodes.split(",")
  for (const code of dictCodeArr) {
    if(!dictTextInfo[code]){
      dictTextInfo[code] = code
      for(const item of dictInfo[code]){
        if(item["itemValue"] && item["itemText"]){
          dictTextInfo[code+"#"+item["itemValue"]] = item["itemText"]
        }else if(item["value"] && item["title"]){
          //树形结构
          dictTextInfo[code+"#"+item["value"]] = item["title"]
          if(item["children"]){
            filterDictChildText(item["children"],dictTextInfo,code)
          }
        }
      }
    }
  }
}
  function filterDictChildText(dictOptions, dictTextInfo,code){
    for(var i=0;i<dictOptions.length;i++){
      if(dictOptions[i]["value"]){
        dictTextInfo[code+"#"+dictOptions[i]["value"]] = dictOptions[i]["title"]
      }
      if(dictOptions[i]["children"]){
        filterDictChildText(dictOptions[i]["children"],dictTextInfo,code)
      }
    }
  }

module.exports = {
  formatTime,
  isNullObj,
  request,
  formVerify,
  string2Date,
  date2String,
  setDictTextInfo
}
